const mongoose = require('mongoose');
const taskScheam = require('../schema/task.js');
const db = require('../config/db.js');
const tasks = mongoose.model('tasks', taskScheam);
class TaskModel {
    //模型化任务表
    /**
     * 创建一条任务数据
     * @param data
     * @returns {Promise.<*>}
     */
    static async createTask(data) {
        data.suppose_end_time = new Date(data.suppose_end_time).getTime();
        let example = new tasks(data);
        try {
            return await example.save()
        }
        catch (err) {
            console.log('任务保存失败');
            return false;
        }
    }
    /**
     * 删除一条任务数据
     * @param id
     * @returns {Promise.<boolean>}
     */
    static async deleteArticle(id) {
        let _id = { _id: mongoose.Types.ObjectId(id) };
        return tasks.findByIdAndRemove(_id);
    }
    /**
     * 更新一条任务数据
     * @param data
     * @returns {Promise.<boolean>}
     */
    static async updateTask(data) {
        let conditions = { _id: mongoose.Types.ObjectId(data._id) };
            let setjson = {};
            (data.md_content !== undefined) && (setjson.md_content = data.md_content);
            (data.html_content !== undefined) && (setjson.html_content = data.html_content);
            (data.update_time !== undefined) && (setjson.update_time = data.update_time);
            (data.title !== undefined) && (setjson.title = data.title);

            let setupdate = { $set: setjson };
            return await tasks.findByIdAndUpdate(conditions, setupdate, {new:true});
    }
   
    /**
     * 查询任务数据
     * @param id
     * @returns {Promise.<*>}
     */
    static async queryTasks(id, _limit, _skip, searchData) {
        return await tasks.find(searchData).count().then(num => {
            return tasks.find(searchData).limit(_limit).skip(_skip).then(result => {
                return {
                    list: result,
                    size: num
                }
            });
        })
    }    
     
}
module.exports = TaskModel

